export default {
	data() {
		return {
			//数据
			uploadNum: 0,
			FileUpload: [],
			FileUploads: [],
			validate: {}, //验证对象
			curriculum: {} ,//课程
      tempName: '',
			fatherIndex: 0, //一级菜单index
			uploadEnclosure:false,//判断是否已经上传附件
		}
	},
	created() { //调用方法
		//初始化课程
		let that = this;
		//获取课程uuid
		let uuid = that.get("newResourcesid");
		that.$post(
				that.urls.getCurriculum, {
					"uuid": uuid
				}
			)
			.then(function(res) {
				if(res.success) {
					that.curriculum = res.data;
					if (res.data != null) {
            that.tempName = res.data.name;
          }
					that.FileUpload = [that.getFileName(res.data.courseware)];
					that.FileUploads = that.convertFileName(res.data.enclosure);
				}
			})
	},
	mounted() {
		let that = this;

		//校验名称重复
		$.validator.addMethod("checkNameRepeat", function(value, element, params) {
			let flg = false;
			if(that.curriculum.id != null && (value == that.tempName)) {
				flg = true;
			} else {
				$.ajax({
					type: "POST",
					async: false,
					url: that.urls.checkCurriculumName,
					data: JSON.stringify({
						"name": value
					}),
					dataType: "json",
					contentType: "application/json",
					success: function(data) {
						if(data.success) {
							flg = !data.data;
						}
					}
				});
			}
			return this.optional(element) || flg;
		}, "当前名称已经使用！");
		//加载表单验证
		that.validate = $("#curriculumForm").validate({
			ignore: [],
			rules: {
				name: { // 课程名称
					required: true,
					maxlength: 20,
					checkNameRepeat: true
				},
				introduction: { // 课程简介
					required: true,
					maxlength: 1000
				},
				courseware: { // 课程课件
					required: true,
					maxlength: 500
				},
				enclosure: { // 课程附件
					required: true,
					maxlength: 500
				}
			},
			messages: {
				name: { // 课程名称
					required: "请输入课程名称",
					maxlength: "请输入长度小于20"
				},
				introduction: { // 课程简介
					required: "请输入简介",
					maxlength: "请输入长度小于1000"
				},
				courseware: { // 课程课件
					required: "请输入课件链接",
					maxlength: "请输入长度小于500"
				},
				enclosure: { // 课程附件
					required: "请上传课程附件",
					maxlength: "请输入长度小于500"
				}
			},
			//errorElement: "em",
			errorPlacement: function(error, element) {
				//alert($(element).val());
        //$(element).parent("div").children("label.error").html("xxx");
			  //error.appendTo(element.parents(".error-box").children(".error-msg"));
        //error.appendTo($(element).parent("div").children("label.error"));
        //error.insertAfter(element);
        error.appendTo( element.parent("div").children("span") );
			}
		});
	},
	updated:function(){
		if(this.getParamValue("fatherIndex")){
			this.fatherIndex=this.getParamValue("fatherIndex");
		}
	},
	methods: { //写函数方法
		touchOffIdInput(n) {
			this.uploadNum = n;
			if(n == 1) {
				$("#handIdFront").click();
			}
		},
    //删除附件
    deleteEnclosure: function(num) {
    	this.uploadEnclosure=true;
      if (num == 1) {
        this.FileUpload = [];
        this.curriculum.courseware = "";
        $("input[name='courseware']").val("");
      } else if (num == 2) {
        this.FileUploads = [];
        this.curriculum.enclosure = "";
        $("input[name='enclosure']").val("");

      }
    },
		/**文件上传(多文件)js**/
		idFrontImg: function(event) {
			var that = this;
			var files = event.currentTarget.files;
      if (!that.fileGlobalFilter(files)) {
        return;
      }
      if (files.length > 5) {
        layer.msg("附件最多只能上传5个！", {
          time: 3000, //3s后自动关闭
        });
        return;
      }
			let formData = new FormData();
			for(var i = 0, len = files.length; i < len; i++) {
				formData.append('fileNames', files[i]);
			}
			let config = {
				headers: {
					'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
				}
			};
			that.$post(
					that.urls.upload,
					formData,
					config
				)
				.then(function(res) {
					if(res.success) {
						let fileInfos = res.data;
						let urls = [];
						let names = [];
						for(var i = 0, len = fileInfos.length; i < len; i++) {
							urls.push(fileInfos[i].url);
							names.push(that.getFileName(fileInfos[i].url));
						}
						that.uploadEnclosure=false;
						that.FileUploads = names;
						that.curriculum.enclosure = urls.join(";");
					}
				})
		},
		Input(n) {
			this.uploadNum = n;
			if(n == 1) {
				$("#IdFront").click();
			}
		},
		/**文件上传（视频，单文件）js**/
		idFront: function(event) {
			var that = this;
			var file = event.currentTarget.files[0];
      if (!that.fileGlobalFilter(file)) {
        return;
      }
			let formData = new FormData();
			formData.append('fileNames', file);
			let config = {
				headers: {
					'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
				}
			};
			that.$post(
					that.urls.upload,
					formData,
					config
				)
				.then(function(res) {
					if(res.success) {
						let fileInfo = res.data[0];
						that.FileUpload = [that.getFileName(fileInfo.url)];
						that.curriculum.courseware = fileInfo.url;
					}
				})
		},
		//保存数据
		saveData: function() {
			let that = this;
			/*if (!this.uploadEnclosure) {
			  return;
      }*/
			let flg = that.validate.form();
			if(flg) {
				let dataObj = that.combinationFormObject(that.validate.currentForm);
				that.$post(
						that.urls.addCurriculum,
						dataObj
					)
					.then(function(res) {
						let msg = "";
						if(res.success) {
							msg = "保存课程成功！";
              that.pressRelease();
						} else {
							msg = "保存课程失败！";
						}
						layer.msg(msg, {
							time: 3000, //3s后自动关闭
						});
					})
			}
		},
		//修改数据
		updateData: function() {
			let that = this;
      /*if (!this.uploadEnclosure) {
        return;
      }*/
			let flg = that.validate.form();
			if(flg) {
				let dataObj = that.combinationFormObject(that.validate.currentForm);
				that.$post(
						that.urls.updateCurriculum,
						dataObj
					)
					.then(function(res) {
						let msg = "";
						if(res.success) {
							msg = "更新课程成功！";
							that.pressRelease();
						} else {
							msg = "更新课程失败！";
						}
						layer.msg(msg, {
							time: 3000, //3s后自动关闭
						});
					})
			}
		},
    //返回课件列表页
    pressRelease: function() {
      var that = this;
      that.$router.push({
        path: "teachingResources?fatherIndex="+this.fatherIndex,
      })
    },
	}
}
